// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <iostream>
#include <memory>
#include <string>

#include <nebula/io/file.h>
#include <nebula/io/stdio.h>
#include <nebula/ipc/reader.h>
#include <nebula/ipc/writer.h>

#include <turbo/utility/status.h>

namespace nebula {

class RecordBatch;

namespace ipc {

// Reads a file on the file system and prints to stdout the stream version of it.
turbo::Status ConvertToStream(const char* path) {
  io::StdoutStream sink;

  TURBO_MOVE_OR_RAISE(auto in_file, io::ReadableFile::open(path));
  TURBO_MOVE_OR_RAISE(auto reader, ipc::RecordBatchFileReader::open(in_file.get()));
  TURBO_MOVE_OR_RAISE(auto writer, ipc::make_stream_writer(&sink, reader->schema(),
                                                           IpcWriteOptions::defaults()));
  for (int i = 0; i < reader->num_record_batches(); ++i) {
    TURBO_MOVE_OR_RAISE(std::shared_ptr<RecordBatch> chunk, reader->read_record_batch(i));
    TURBO_RETURN_NOT_OK(writer->write_record_batch(*chunk));
  }
  return writer->close();
}

}  // namespace ipc
}  // namespace nebula

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage: file-to-stream <input nebula file>" << std::endl;
    return 1;
  }
  turbo::Status status = nebula::ipc::ConvertToStream(argv[1]);
  if (!status.ok()) {
    std::cerr << "Could not convert to stream: " << status.to_string() << std::endl;
    return 1;
  }
  return 0;
}
